package multi_thread.advanced;

import java.time.LocalDate;
import java.util.concurrent.*;

/**
 * @author Cheng Jun
 * Description: 利用Callable接口，实现创建线程。Callable接口具有返回值和抛出异常的特点
 * @version 1.0
 * @date 2020/2/29 13:11
 */
public class CallableExample implements Callable<Integer> {


    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        // FutureTask implements RunnableFuture<V>
        // RunnableFuture<V> extends Runnable, Future<V>
        CallableExample callableExample = new CallableExample();
        // FutureTask is a cancellable asynchronous computation. FutureTask 可取消的异步计算任务
        FutureTask<Integer> ageFutureTask = new FutureTask<>(callableExample);
        new Thread(ageFutureTask).start();
        // the get methods will block if the computation has not yet completed
        Integer age = ageFutureTask.get();
        Integer age1 = ageFutureTask.get();
        // Integer age = ageFutureTask.get(1, TimeUnit.SECONDS);
        System.out.println("ageFutureTask.get() 会造成阻塞，一直等Callable的call方法运行完成");
        System.out.println(age);
    }

    @Override
    public Integer call() throws Exception {
        // 演示除0异常
        // int byZero = 10 / 0;
        // 计算我的年龄
        TimeUnit.SECONDS.sleep(2);
        return LocalDate.now().getYear() - 1994;
    }

}

